import asyncio
import logging
import threading

from fastapi import FastAPI
import uvicorn
from tortoise.contrib.fastapi import register_tortoise

from config import TORTOISE_ORM, SERVER_PORT, SERVER_HOST, LOG_DIR
from routers.order import order
from routers.customer import customer
from routers.kumquat import kumquat

from uvicorn.config import LOGGING_CONFIG

from toolkit import basic_log_config

app = FastAPI()
LOGGING_CONFIG["formatters"]["default"]["fmt"] = "%(asctime)s - %(levelprefix)s %(message)s"
app.include_router(customer, prefix='/customer', tags=["About Customer"])
app.include_router(kumquat, prefix='/kumquat', tags=["About Sweetie"])
app.include_router(order, prefix='/order', tags=["About Order"])

register_tortoise(
    app,
    config=TORTOISE_ORM,
    generate_schemas=True,
    add_exception_handlers=True,
)

# origins = [
#     "http://localhost:8080",  # 允许的来源
#     "http://127.0.0.1:8080",  # 可以添加多个来源
# ]
#
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=origins,  # 允许的来源
#     allow_credentials=True,  # 允许发送 cookies
#     allow_methods=["*"],  # 允许的方法
#     allow_headers=["*"],  # 允许的头部
# )


@app.get("/users/{username}")
async def read_user(username: str):
    return {"message": f"Hello {username}"}


@app.get("/", tags=["这是一个Hello World"], summary="Hello nothing much",
         description="Hello test",
         response_description="返回Hello world")
async def hello():
    return {"Hello World"}


def run_uvicorn():
    uvicorn.run("run:app", port=SERVER_PORT, host=SERVER_HOST, reload=True)


async def on_startup():
    logging.info("Uvicorn server is starting...")
    await asyncio.sleep(1)  # 确保服务器有足够的时间启动
    logging.info("Uvicorn server has started. Starting PySide6 application...")
    pyside_thread = threading.Thread(target=run_pyside_app)
    pyside_thread.daemon = True
    pyside_thread.start()


def run_pyside_app():
    from kumquat_king_pyside6 import main
    main.main()


if __name__ == "__main__":
    basic_log_config(LOG_DIR, False)
    # uvicorn.run("run:app", port=SERVER_PORT, host=SERVER_HOST, reload=True)
    asyncio.run(on_startup())
    run_uvicorn()
